<template>
  <view class="box">
    <view class="container">
      <view class="container_box">
        <view class="container_box_image">
          <image v-if="RecordCategoryList.previewImage" :src="RecordCategoryList.previewImage" mode="aspectFill"></image>
          <image v-else src="http://qichong-1256206693-1256206693.cos.ap-nanjing.myqcloud.com/upload/20210617/a1b0aedabc466612a506a75eda513e72.png" mode="aspectFill"></image>
        </view>

        <!-- title -->
        <view class="container_title">
          <h1>{{RecordCategoryList.productName}}</h1>
          <image v-if="RecordCategoryList.sex === '0'" src="/static/images/mine/nan.png" mode="aspectFill"></image>
          <image v-if="RecordCategoryList.sex === '1'" src="/static/images/mine/nv.png" mode="aspectFill"></image>
        </view>

        <!-- 标签 -->
        <view class="container_label">
          <text v-if="RecordCategoryList.labels.length !== 0" class="container_label_box"
            v-for="(item,i) in RecordCategoryList.labels" :key="i">
            {{item}}
          </text>
          <text v-if="RecordCategoryList.labels.length == 0" class="container_label_box">宠物还没有标签哦 ~</text>
        </view>

        <!-- 时间 -->
        <view class="container_time">
          <view class="container_time_birth">
            <text>我已经 <text
                style="font-weight: bold;">{{RecordCategoryList.ageStr?RecordCategoryList.ageStr : '未知'}}</text>
              大了～</text>
          </view>
          <view class="container_time_home">
            <text v-if="RecordCategoryList.arriveHomeStr">我来到这个家已经 <text
                style="font-weight: bold;">{{RecordCategoryList.arriveHomeStr}}</text>了～</text>
            <text v-else>我来到这个家 <text style="font-weight: bold;">还不到一个月</text>哦～</text>
          </view>
        </view>

        <!-- 情况 -->
        <view class="container_introduce">
          <view class="container_introduce_box">
            <h1>{{RecordCategoryList.neuter === '0'? '已绝育':'未绝育'}}</h1>
            <text>绝育</text>
          </view>
          <view class="container_introduce_box">
            <h1>{{RecordCategoryList.category.categoryName? RecordCategoryList.category.categoryName : '未知'}}</h1>
            <text>品种</text>
          </view>
          <view class="container_introduce_box">
            <h1>{{RecordCategoryList.coatColor? RecordCategoryList.coatColor : '未知'}}</h1>
            <text>毛色</text>
          </view>
        </view>

      </view>
      <!-- 专属通证 -->
      <view class="container_bottom" v-cloak>
        <text>专属通证：{{RecordCategoryList.token}}</text>
      </view>

    </view>

    <view class="box_image">
    </view>


    <!-- 线 -->
    <!-- <view class="container_wire">
      <view class="container_wire_image">
        <image src="/static/images/mine/mao3.png" mode="aspectFill"></image>
      </view>
    </view> -->
    <view class="new_pet">
      <button type="success" class="new_pet_button" @click="userinvitation">炫耀一下</button>
    </view>

    <canvas canvas-id="myCanvas" style="width: 690px;height:1200px;position: fixed;top: -10000px;"></canvas>


    <van-popup :show="showShareImg" round @close="onShareClose">
      <view class="popup_title">
        <text>身份卡海报</text>
      </view>
      <view class="popup_image">
        <image :src="canvasToTempFilePathImage" mode="widthFix"></image>
      </view>
      <view class="popup_button" @click="saveShareImg(canvasToTempFilePathImage)">
        <button type="default">保存图片，分享好友</button>
      </view>
    </van-popup>

  </view>
</template>

<script>
  import {
    storePethealthItem
  } from '@/api/home.js'
  import {
    mapActions,
    mapGetters
  } from 'vuex'
  export default {
    data() {
      return {
        RecordCategoryList: {},
        ctx: null,
        canvasToTempFilePathImage: '',
        showShareImg: false,
        openStatus: true,
        headUrl: '',
        showShare: false,
        options: [{
            name: '微信',
            icon: 'wechat'
            // openType: 'share'
          },
          {
            name: '朋友圈',
            icon: 'wechat'
          }
        ],
      };
    },
    // #ifdef MP
    //发送给朋友
    onShareAppMessage: function() {
      return {
        title: "奇宠日记",
        path: '/pages/tabbar/index/index',
        imageUrl: this.canvasToTempFilePathImage
      };
    },
    //分享到朋友圈
    onShareTimeline: function() {
      return {
        title: "奇宠日记",
        path: '/pages/tabbar/index/index',
        imageUrl: this.canvasToTempFilePathImage
      };
    },
    // #endif
    onLoad(option) {
      // console.log(option.id)
      this.ongetIdentity(option.id)
    },
    computed: {
      // ...mapGetters('m_pet', ['RecordCategoryList'])
    },
    methods: {
      ...mapActions('m_pet', ['GetCategoryList']),
      //海报文字超出显示省略号
      canvasWraptitleText(canvas, text, x, y, maxWidth, lineHeight, maxRowNum) {
        if (typeof text != 'string' || typeof x != 'number' || typeof y != 'number') {
          return;
        }
        canvas.font = 'normal 26px sans-serif'; //绘制文字的字号和大小
        // 字符分隔为数组
        let arrText = text.split('');
        let line = '';
        let rowNum = 1
        for (let n = 0; n < arrText.length; n++) {
          let testLine = line + arrText[n];
          let metrics = canvas.measureText(testLine);
          let testWidth = metrics.width;
          if (testWidth > maxWidth && n > 0) {
            if (rowNum >= maxRowNum) {
              let arrLine = testLine.split('')
              // arrLine.splice(-2)
              let newTestLine = arrLine.join("")
              newTestLine += "..."
              canvas.fillText(newTestLine, x, y);
              return
            }
            canvas.fillText(line, x, y);
            line = arrText[n];
            y += lineHeight;
            rowNum += 1
          } else {
            line = testLine;
          }
        }
        canvas.fillText(line, x, y);
      },
      ongetIdentity(id) {
        storePethealthItem(id).then(res => {
          this.RecordCategoryList = res.data
          this.RecordCategoryList.labels = res.data.labels.split(',')
          let type = this
          // 头像
          uni.getImageInfo({
            src: type.RecordCategoryList.previewImage,
            success: function(res) {
              // console.log(res);
              type.headUrl = res.path
              console.log(type.headUrl)
            }
          });
        }).catch(err => err)
      },
      // 邀请
      userinvitation() {
        let self = this;
        // 点击生成海报数据埋点
        let gengrUrl = self.RecordCategoryList.sex === '0' ? '/static/images/mine/nan.png' :
          '/static/images/mine/nv.png'
        let neuter = self.RecordCategoryList.neuter === '0' ? '已绝育' : '未绝育'
        let characterMargin = 145

        // console.log(codeUrl)
        if (!self.ctx) {
          uni.showLoading({
            title: '生成中...'
          });
          Promise.all([gengrUrl]).then(function(result) {
            const ctx = uni.createCanvasContext('myCanvas');

            let avatarurl_width = 110, //绘制的头像宽度
              avatarurl_heigth = 110, //绘制的头像高度
              avatarurl_x = 160, //绘制的头像在画布上的位置
              avatarurl_y = 285; //绘制的头像在画布上的位置

            ctx.drawImage('http://qichong-1256206693-1256206693.cos.ap-nanjing.myqcloud.com/upload/20210703/35674f06cd7da3e7f5025e876208b0c4.png', -3, 0, 700, 1200); // 背景图片需要本地

            ctx.save()
            ctx.beginPath(); //开始绘制
            //先画个圆   前两个参数确定了圆心 （x,y） 坐标  第三个参数是圆的半径  四参数是绘图方向  默认是false，即顺时针
            ctx.arc(avatarurl_width / 2 + avatarurl_x, avatarurl_heigth / 2 + avatarurl_y, avatarurl_width / 2, 0,
              Math.PI * 2, );
            // ctx.fill() //保证图片无bug填充
            ctx.clip(); //画了圆 再剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内
            if (self.headUrl) {
              ctx.drawImage(self.headUrl, avatarurl_x, avatarurl_y, avatarurl_width, avatarurl_heigth) // 推进去图片
            } else {
              // console.log(self.headUrl)
              ctx.drawImage('/static/images/mine/touxiang1.png', avatarurl_x, avatarurl_y, avatarurl_width,
                avatarurl_heigth) // 推进去图片
            }

            ctx.restore()
            ctx.closePath();
            // console.log(self.headUrl)
            // ctx.font = 'normal normal 24px sans-serif';
            // ctx.setFillStyle('#1F8DFE'); // 文字颜色
            // ctx.fillText(self.RecordCategoryList.name, 55, 700); // 绘制文字
            ctx.save()
            ctx.beginPath();

            ctx.font = 'normal bold 40px sans-serif';
            ctx.setFillStyle('#393939');
            ctx.fillText(self.RecordCategoryList.productName, 300, 325);

            // ctx.font = 'normal 30px sans-serif';
            // ctx.setFillStyle('#8B8B8B');
            // ctx.fillText(self.RecordCategoryList.breedDesc, 315, 383);
            if (self.RecordCategoryList.category.categoryName) {
              self.canvasWraptitleText(ctx, self.RecordCategoryList.category.categoryName, 300, 383, 110, 50, 1)
            } else {
              self.canvasWraptitleText(ctx, '未知', 300, 383, 110, 50, 1)
            }

            ctx.drawImage(gengrUrl, 460, 353, 40, 40);

            // 设置线宽
            ctx.lineWidth = 1;
            // 设置间距（参数为无限数组，虚线的样式会随数组循环）
            ctx.setLineDash([10, 10]);
            // 移动画笔至坐标 x20 y20 的位置
            ctx.moveTo(140, 438);
            // 绘制到坐标 x20 y100 的位置
            ctx.lineTo(545, 438);
            // 填充颜色
            ctx.strokeStyle = "#3D3D3D";

            ctx.font = 'normal 26px sans-serif';
            ctx.setFillStyle('#000');
            ctx.fillText('#' + neuter + '#', 145, 490);

            if (self.RecordCategoryList.coatColor) {
              ctx.font = 'normal 26px sans-serif';
              ctx.setFillStyle('#000');
              ctx.fillText('#' + self.RecordCategoryList.coatColor + '#', 275, 490);
            } else {
              ctx.font = 'normal 30px sans-serif';
              ctx.setFillStyle('#000');
              ctx.fillText('未知', 275, 490);
            }

            // 性格标签
            if (self.RecordCategoryList.labels.length !== 0) {
              self.RecordCategoryList.labels.forEach((item, i) => {
                if (i <= 2) {
                  // ctx.font = 'normal 28px sans-serif';
                  ctx.setFillStyle('#FF6666');
                  if (i == 0) {
                    // return ctx.fillText('#' + item.name + '#', characterMargin, 500);
                    return self.canvasWraptitleText(ctx, '#' + item + '#', characterMargin, 540, 80, 50, 1)
                  }
                  // ctx.fillText('#' + item.name + '#', characterMargin += 130, 500);
                  self.canvasWraptitleText(ctx, '#' + item + '#', characterMargin += 130, 540, 80, 50, 1)
                }
              })
            } else {
              ctx.font = 'normal 30px sans-serif';
              ctx.setFillStyle('#FF6666');
              ctx.fillText('宠物还没有性格标签哦~', characterMargin, 540);
            }


            // 设置线宽
            ctx.lineWidth = 1;
            // 设置间距（参数为无限数组，虚线的样式会随数组循环）
            ctx.setLineDash([10, 10]);
            // 移动画笔至坐标 x20 y20 的位置
            ctx.moveTo(140, 570);
            // 绘制到坐标 x20 y100 的位置
            ctx.lineTo(545, 570);
            // 填充颜色
            ctx.strokeStyle = "#3D3D3D";


            ctx.font = 'normal 30px sans-serif';
            ctx.setFillStyle('#8c8c8c');
            ctx.fillText('我已经 ' + self.RecordCategoryList.ageStr + ' 大了 ~', 145, 623);

            if (self.RecordCategoryList.arriveHomeStr) {
              ctx.font = 'normal 30px sans-serif';
              ctx.setFillStyle('#8c8c8c');
              ctx.fillText('我来到这个家已经 ' + self.RecordCategoryList.arriveHomeStr + ' 了 ~', 145, 673);
            } else {
              ctx.font = 'normal 30px sans-serif';
              ctx.setFillStyle('#8c8c8c');
              ctx.fillText('我来到这个家还不到一个月哦 ~', 145, 673);
            }


            // 设置线宽
            ctx.lineWidth = 1;
            // 设置间距（参数为无限数组，虚线的样式会随数组循环）
            ctx.setLineDash([10, 10]);
            // 移动画笔至坐标 x20 y20 的位置
            ctx.moveTo(140, 705);
            // 绘制到坐标 x20 y100 的位置
            ctx.lineTo(545, 705);
            // 填充颜色
            ctx.strokeStyle = "#3D3D3D";

            ctx.font = 'normal 30px sans-serif';
            ctx.setFillStyle('#3D3D3D');
            ctx.fillText('专属通证:' + self.RecordCategoryList.token, 145, 770);

            // ctx.font = 'normal 30px sans-serif';
            // ctx.setFillStyle('#3D3D3D');
            // ctx.fillText(self.RecordCategoryList.token, 290, 770);

            // 设置线宽
            ctx.lineWidth = 1;
            // 设置间距（参数为无限数组，虚线的样式会随数组循环）
            ctx.setLineDash([10, 10]);
            // 移动画笔至坐标 x20 y20 的位置
            ctx.moveTo(140, 815);
            // 绘制到坐标 x20 y100 的位置
            ctx.lineTo(545, 815);
            // 填充颜色
            ctx.strokeStyle = "#3D3D3D";

            ctx.stroke();
            ctx.closePath();

            ctx.draw(false, function() {
              // canvas画布转成图片并返回图片地址
              uni.canvasToTempFilePath({
                canvasId: 'myCanvas',
                success: function(res) {
                  self.canvasToTempFilePathImage = res.tempFilePath;
                  self.showShareImg = true;
                  // console.log(res.tempFilePath, 'canvasToTempFilePath');
                  uni.showToast({
                    title: '绘制成功'
                  });
                },
                fail: function() {
                  uni.showToast({
                    title: '绘制失败'
                  });
                },
                complete: function() {
                  uni.hideLoading();
                  uni.hideToast();
                }
              });
            });
          });
        }
      },
      onShareClose() {
        this.showShareImg = false
      },
      onShowClose() {
        this.showShare = false
      },
      // 保存到系统相册
      saveShareImg: function(canvasToTempFilePath) {
        let self = this;
        // 数据埋点点击保存海报
        self.saveId = '保存学情海报';
        // 获取用户是否开启用户授权相册
        if (!self.openStatus) {
          wx.openSetting({
            success: result => {
              if (result) {
                if (result.authSetting['scope.writePhotosAlbum'] === true) {
                  self.openStatus = true;
                  wx.saveImageToPhotosAlbum({
                    filePath: canvasToTempFilePath,
                    success() {
                      self.showShareImg = false;
                      wx.showToast({
                        title: '图片保存成功，快去分享到朋友圈吧~',
                        icon: 'none',
                        duration: 2000
                      });
                    },
                    fail() {
                      wx.showToast({
                        title: '保存失败',
                        icon: 'none'
                      });
                    }
                  });
                }
              }
            },
            fail: () => {},
            complete: () => {}
          });
        } else {
          wx.getSetting({
            success(res) {
              // 如果没有则获取授权
              if (!res.authSetting['scope.writePhotosAlbum']) {
                wx.authorize({
                  scope: 'scope.writePhotosAlbum',
                  success() {
                    self.openStatus = true;
                    wx.saveImageToPhotosAlbum({
                      filePath: canvasToTempFilePath,
                      success() {
                        self.showShareImg = false;
                        wx.showToast({
                          title: '图片保存成功，快去分享到朋友圈吧~',
                          icon: 'none',
                          duration: 2000
                        });
                      },
                      fail() {
                        wx.showToast({
                          title: '保存失败',
                          icon: 'none'
                        });
                      }
                    });
                  },
                  fail() {
                    // 如果用户拒绝过或没有授权，则再次打开授权窗口
                    self.openStatus = false;
                    // console.log('请设置允许访问相册');
                    wx.showToast({
                      title: '请设置允许访问相册',
                      icon: 'none'
                    });
                  }
                });
              } else {
                // 有则直接保存
                self.openStatus = true;
                wx.saveImageToPhotosAlbum({
                  filePath: canvasToTempFilePath,
                  success() {
                    self.showShareImg = false;
                    wx.showToast({
                      title: '图片保存成功，快去分享到朋友圈吧~',
                      icon: 'none',
                      duration: 2000
                    });
                  },
                  fail() {
                    wx.showToast({
                      title: '保存失败',
                      icon: 'none'
                    });
                  }
                });
              }
            },
            fail(err) {
              // console.log(err);
            }
          });
        }
      },
    }
  }
</script>

<style lang="scss">
  .box {
    position: relative;

    .box_image {
      position: absolute;
      top: 0;
      width: 750rpx;
      height: 518rpx;
      background: linear-gradient(180deg, rgba(253, 211, 56, 1) 0%, rgba(253, 211, 56, 1) 100%);
      border-top-left-radius: 0px;
      border-top-right-radius: 0px;
      border-bottom-right-radius: 200rpx;
      border-bottom-left-radius: 200rpx;
    }
  }

  .container {
    padding: 131rpx 48rpx 0;
    position: relative;
    display: flex;
    justify-content: center;

    .container_box {
      position: relative;
      z-index: 2;
      width: 654rpx;
      // height: 650rpx;
      background-color: rgba(255, 255, 255, 1);
      box-shadow: 0px 0px 20rpx 3rpx rgba(0, 0, 0, 0.04);
      border-radius: 50rpx;
      display: flex;
      align-items: center;
      flex-direction: column;

      .container_box_image {
        position: absolute;
        top: -85rpx;
        width: 164rpx;
        height: 164rpx;
        border-radius: 50%;
        overflow: hidden;
        border: 15rpx solid #fff;

        image {
          width: 100%;
          height: 100%;

        }
      }

      .container_title {
        position: relative;
        padding-top: 123rpx;
        font-size: 48rpx;
        margin-bottom: 20rpx;

        image {
          position: absolute;
          top: 138rpx;
          right: -54rpx;
          width: 40rpx;
          height: 40rpx;
        }
      }

      .container_label {
        width: 474rpx;
        display: flex;
        flex-wrap: wrap;
        justify-content: space-around;

        .container_label_box {
          padding: 2rpx 36rpx;
          background-color: rgba(255, 102, 102, 0.1);
          color: rgba(255, 102, 102, 0.8);
          border-radius: 217rpx;
          font-size: 26rpx;
          margin: 15rpx 0;
        }
      }

      .container_time {
        text-align: center;
        margin-top: 20rpx;
        padding-bottom: 40rpx;
        font-size: 30rpx;
        border-bottom: 1px dashed rgba(61, 61, 61, 0.15);

        .container_time_birth {
          margin: 10rpx 0 20rpx;
        }

        .container_time_home {
          // margin: 10rpx 0;
        }
      }

      .container_introduce {
        width: 100%;
        height: 180rpx;
        display: flex;

        .container_introduce_box {
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;

          h1 {
            font-size: 34rpx;
            margin-bottom: 10rpx;
          }

          text {
            font-size: 30rpx;
            color: rgba(61, 61, 61, 0.5);
          }
        }
      }
    }

    .container_bottom {
      position: absolute;
      bottom: -75rpx;
      width: 464rpx;
      height: 249rpx;
      background-color: rgba(255, 255, 255, 1);
      box-shadow: 0px 0px 20rpx 3rpx rgba(0, 0, 0, 0.04);
      border-radius: 50rpx;
      z-index: -1;

      text {
        display: inline-block;
        width: 100%;
        position: absolute;
        bottom: 20rpx;
        font-size: 26rpx;
        text-align: center;
      }
    }
  }

  // .container_wire {
  //   position: absolute;
  //   bottom: -260rpx;
  //   width: 100%;
  //   height: 2px;
  //   box-sizing: border-box;
  //   background-color: #f6f6f6;
  //   display: flex;
  //   justify-content: center;
  //   align-items: center;

  //   .container_wire_image {
  //     position: absolute;
  //     width: 102rpx;
  //     height: 102rpx;
  //     background-color: #fff;
  //     display: flex;
  //     justify-content: center;
  //     align-items: center;

  //     image {
  //       width: 90rpx;
  //       height: 100rpx;
  //     }
  //   }
  // }

  /deep/ .van-pupop,
  .van-popup--center {
    padding: 36rpx 85rpx !important;
  }

  /deep/ .popup_title {
    width: 100%;
    text-align: center;
    font-size: 44rpx;
    color: rgba(61, 61, 61, 0.8);
    font-weight: bold;
  }

  /deep/ .popup_image {
    width: 433rpx;
    height: 764rpx;
    margin-top: 26rpx;

    image {
      width: 100%;
      height: 100%;
    }
  }

  /deep/ .popup_button {
    width: 433rpx;
    height: 74rpx;

    button {
      width: 100%;
      height: 100%;
      line-height: 74rpx;
      border-radius: 226rpx;
      background-color: #FDD338;
      color: rgba(61, 61, 61, 1);
      font-size: 32rpx;
      margin-top: 27rpx;
      font-weight: bold;
    }
  }


  .new_pet {
    position: fixed;
    bottom: 0;
    padding: 24rpx;
    width: 750rpx;
    height: 128rpx;
    box-sizing: border-box;
    background-color: #fff;

    .new_pet_button {
      width: 702rpx;
      height: 82rpx;
      background-color: #FDD338;
      // border-radius: 6px;
      color: rgba(61, 61, 61, 0.8);
      line-height: 82rpx;
      border-radius: 82rpx;
      font-size: 16px;
      font-weight: 500;
    }
  }
</style>
